package com.deparse.dpframe.ui.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.deparse.dpframe.R;
import com.deparse.dpframe.bean.DPView;
import com.deparse.dpframe.common.DPConsts;
import com.deparse.dpframe.common.DPBusEvent;
import com.deparse.dpframe.libs.SystemBarTintManager;
import com.deparse.dpframe.ui.widget.photoview.PhotoView;
import com.deparse.dpframe.ui.widget.photoview.PhotoViewAttacher;
import com.deparse.dpframe.utils.DPImageUtil;
import com.deparse.dpframe.utils.DPLogUtil;
import com.deparse.dpframe.utils.DPPicassoUtil;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 * Created by MartinDKent on 2016/1/16.
 */
public class DPBaseActivity extends AppCompatActivity {

    private Map<Integer, DPView> DPViewCacher = new HashMap<>(20);
    private Map<Integer, View> viewCacher = new HashMap<>(20);

    private LayoutInflater inflater;
    private boolean onCreateExecuted = false;
    private boolean isAppBackground;

    private Map<Integer, Integer> requestCodes = new HashMap<>();
    private boolean isJugingBackground = false;

    private FragmentManager fragmentManager = null;

    private RelativeLayout rootView;

    private PhotoView imagePreviewDialog;

    private Bitmap imagePreviewDialogBitmap;

    private File imagePreviewDialogBitmapTmpFile;
    private InputMethodManager mInputMethodManager;

    public void showImagePreviewDialog(String path) {
        DPLogUtil.enter(path);
        if (null != imagePreviewDialog) {
            if (null != imagePreviewDialog.getParent()) {
                removeInRootView(imagePreviewDialog);
            }
            imagePreviewDialog = null;
        }
        imagePreviewDialog = new PhotoView(this);
        imagePreviewDialog.setBackgroundColor(Color.argb(128, 0, 0, 0));
        imagePreviewDialog.setVisibility(View.GONE);
        imagePreviewDialog.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        addInRootView(imagePreviewDialog, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        imagePreviewDialog.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() {
            @Override
            public void onViewTap(View view, float x, float y) {
                hideImagePreviewDialog();
            }
        });

        Bitmap bitmap = DPImageUtil.getBitmapFromFile(path);
        imagePreviewDialog.setImageBitmap(bitmap);

//        imagePreviewDialogBitmapTmpFile = DPFileUtil.makeCacheFile(this, "pub_act", System.currentTimeMillis() + ".jpg");
//        DPImageUtil.saveBitmapToFile(bitmap, imagePreviewDialogBitmapTmpFile);
//
//        Picasso.with(this).load(imagePreviewDialogBitmapTmpFile).into(imagePreviewDialog);
        imagePreviewDialog.setVisibility(View.VISIBLE);
    }

    public void showImagePreviewHttpDialog(String path) {
        DPLogUtil.enter(path);
        if (null != imagePreviewDialog) {
            if (null != imagePreviewDialog.getParent()) {
                removeInRootView(imagePreviewDialog);
            }
            imagePreviewDialog = null;
        }
        imagePreviewDialog = new PhotoView(this);
        imagePreviewDialog.setBackgroundColor(Color.argb(128, 0, 0, 0));
        imagePreviewDialog.setVisibility(View.GONE);
        imagePreviewDialog.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        addInRootView(imagePreviewDialog, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        imagePreviewDialog.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() {
            @Override
            public void onViewTap(View view, float x, float y) {
                hideImagePreviewDialog();
            }
        });

//        Bitmap bitmap = DPImageUtil.getBitmapFromFile(path);
//        imagePreviewDialog.setImageBitmap(bitmap);

//        imagePreviewDialogBitmapTmpFile = DPFileUtil.makeCacheFile(this, "pub_act", System.currentTimeMillis() + ".jpg");
//        DPImageUtil.saveBitmapToFile(bitmap, imagePreviewDialogBitmapTmpFile);
//
        DPPicassoUtil.with(this).load(path).into(imagePreviewDialog);
        imagePreviewDialog.setVisibility(View.VISIBLE);
    }

    public boolean hideImagePreviewDialog() {
        if (null != imagePreviewDialog && View.VISIBLE == imagePreviewDialog.getVisibility()) {
            if (null != imagePreviewDialogBitmapTmpFile) {
                imagePreviewDialogBitmapTmpFile.delete();
            }
            Animation anim = AnimationUtils.loadAnimation(this, android.R.anim.fade_out);
            anim.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    imagePreviewDialog.setVisibility(View.GONE);
                    removeInRootView(imagePreviewDialog);
                    imagePreviewDialog = null;
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
            imagePreviewDialog.startAnimation(anim);

            if (null != imagePreviewDialogBitmap) {
                if (!imagePreviewDialogBitmap.isRecycled()) {
                    imagePreviewDialogBitmap.recycle();
                }
                imagePreviewDialogBitmap = null;
            }
            return true;
        }
        return false;
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        return hideImagePreviewDialog() || super.dispatchKeyEvent(event);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            DPBaseActivity.this.handleMessage(msg);
        }
    };

    /**
     * handleMessage
     *
     * @param msg
     */
    protected void handleMessage(Message msg) {

    }

    /**
     * sendEmptyMessage
     *
     * @param what
     */
    protected void sendEmptyMessage(int what) {
        handler.sendEmptyMessage(what);
    }

    /**
     * sendEmptyMessageDelayed
     *
     * @param what
     * @param delay
     */
    protected void sendEmptyMessageDelayed(int what, long delay) {
        handler.sendEmptyMessageDelayed(what, delay);
    }

    /**
     * sendMessage
     *
     * @param msg
     */
    protected void sendMessage(Message msg) {
        handler.sendMessage(msg);
    }

    /**
     * sendMessageDelayed
     *
     * @param msg
     * @param delay
     */
    protected void sendMessageDelayed(Message msg, long delay) {
        handler.sendMessageDelayed(msg, delay);
    }

    /**
     * removeMessage
     *
     * @param waht
     */
    protected void removeMessage(int waht) {
        handler.removeMessages(waht);
    }

    /**
     * post
     *
     * @param runnable
     */
    public void post(Runnable runnable) {
        handler.post(runnable);
    }

    /**
     * postDelayed
     *
     * @param runnable
     * @param delayMillis
     */
    public void postDelayed(Runnable runnable, long delayMillis) {
        handler.postDelayed(runnable, delayMillis);
    }

    public int getScreenWide() {
        if (DPConsts.SCREEN_WIDE == -1) {
            DPLogUtil.d("DPConsts.SCREEN_WIDE==" + "no get wide");
            return -1;
        } else {
            DPLogUtil.d("DPConsts.SCREEN_WIDE==" + DPConsts.SCREEN_WIDE);
            return DPConsts.SCREEN_WIDE;
        }

    }

    public int getScreenHeight() {
        if (DPConsts.SCREEN_HEIGHT == -1) {
            DPLogUtil.d("DPConsts.SCREEN_WIDE==" + "no get height");
            return -1;
        } else {
            DPLogUtil.d("DPConsts.SCREEN_HEIGHT==" + DPConsts.SCREEN_HEIGHT);
            return DPConsts.SCREEN_HEIGHT;
        }
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);

        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        DPConsts.SCREEN_WIDE = metric.widthPixels;     // 屏幕宽度（像素）
        DPConsts.SCREEN_HEIGHT = metric.heightPixels;   // 屏幕高度（像素）
        DPConsts.SCREEN_DENSITY = metric.density;      // 屏幕密度（0.75 / 1.0 / 1.5）
        int densityDpi = metric.densityDpi;  // 屏幕密度DPI（120 / 160 / 240）

        mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        rootView = new RelativeLayout(this);
        rootView.setFitsSystemWindows(true);
        rootView.setClipToPadding(true);
        rootView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        super.setContentView(rootView);

        inflater = getLayoutInflater();
        onCreateExecuted = true;
        fragmentManager = getSupportFragmentManager();

    }

    private SystemBarTintManager tintManager;

    /**
     * setStausBarBackgroundColor
     *
     * @param color
     */
    @TargetApi(19)
    protected void setStausBarBackgroundColor(int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintColor(color);
            tintManager.setStatusBarTintEnabled(true);
        }
    }

    private class DPFinishActivityEvent {

    }

    @Subscriber(tag = "onEventMainThread")
    public void onEventMainThread(DPFinishActivityEvent event) {
        finish();
    }

    /**
     * onEventMainThread
     *
     * @param event
     */
    @Subscriber(tag = "onEventMainThread")
    public void onEventMainThread(DPBusEvent event) {
        String args = "";
        if (null != event.args) {
            for (int i = 0; i < event.args.length; i++) {
                args += (event.args[i] + ",");
            }
        }
        if (args.endsWith(",")) {
            args = args.substring(0, args.length() - 1);
        }
        DPLogUtil.d("what=" + event.what + ",args=[" + args + "],obj=" + event.obj);
    }

    /**
     * postBusEvent
     *
     * @param event
     */
    public void postBusEvent(DPBusEvent event) {
        EventBus.getDefault().post(event, "onEventMainThread");
    }

    /**
     * postBusEventDelayed
     *
     * @param event
     * @param duration
     */
    public void postBusEventDelayed(final DPBusEvent event, final int duration) {
        postDelayed(new Runnable() {
            @Override
            public void run() {
                postBusEvent(event);
            }
        }, duration);
    }

    /**
     * finishAllActivities
     */
    protected void finishAllActivities() {
        EventBus.getDefault().post(new DPFinishActivityEvent(), "onEventMainThread");
    }

    /**
     * setContentView
     *
     * @param layoutResID
     */
    @Override
    public void setContentView(int layoutResID) {
        rootView.removeAllViewsInLayout();
        rootView.addView(inflate(layoutResID), new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }

    /**
     * setContentView
     *
     * @param view
     */
    @Override
    public void setContentView(View view) {
        rootView.removeAllViewsInLayout();
        rootView.addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }

    /**
     * setContentView
     *
     * @param view
     * @param params
     */
    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        rootView.removeAllViewsInLayout();
        rootView.addView(view, params);
    }

    /**
     * addInRootView
     *
     * @param view
     * @param params
     */
    public void addInRootView(View view, ViewGroup.LayoutParams params) {
        rootView.addView(view, params);
    }

    /**
     * addInRootView
     *
     * @param view
     * @param index
     * @param params
     */
    public void addInRootView(View view, int index, ViewGroup.LayoutParams params) {
        rootView.addView(view, index, params);
    }

    public void removeInRootView(View view) {
        rootView.removeView(view);
        view = null;
    }

    public void removeInRootView(int index) {
        rootView.removeViewAt(index);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (onCreateExecuted) {
            onFirstResume();
        } else {
            onAnotherResume();
        }
    }

    /**
     * onFirstResume
     */
    protected void onFirstResume() {

    }

    /**
     * onAnotherResume
     */
    protected void onAnotherResume() {
        AsyncTask task = new AsyncTask() {
            @Override
            protected Object doInBackground(Object[] params) {
                while (isJugingBackground()) {
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                return null;
            }

            @Override
            protected void onPostExecute(Object o) {
                super.onPostExecute(o);
                if (isAppBackground()) {
                    setIsAppBackground(false);
                    onReturnFromOtherApp();
                } else {
                    onReturnFromSelf();
                }
            }
        };
        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    /**
     * onReturnFromSelf
     */
    protected void onReturnFromSelf() {

    }

    /**
     * onReturnFromOtherApp
     */
    protected void onReturnFromOtherApp() {

    }

    /**
     * onStop
     */
    @Override
    protected void onStop() {
        super.onStop();
        onCreateExecuted = false;

        AsyncTask task = new AsyncTask() {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                setIsJugingBackground(true);
            }

            @Override
            protected Object doInBackground(Object[] params) {
                return jugeBackground();
            }

            @Override
            protected void onPostExecute(Object o) {
                super.onPostExecute(o);
                setIsAppBackground((boolean) o);
                setIsJugingBackground(false);
            }
        };
        task.execute();
    }

    /**
     * onDestroy
     */
    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
    }

    /**
     * isJugingBackground
     *
     * @return
     */
    private boolean isJugingBackground() {
        return isJugingBackground;
    }

    /**
     * setIsJugingBackground
     *
     * @param isJuging
     */
    private void setIsJugingBackground(boolean isJuging) {
        this.isJugingBackground = isJuging;
    }

    /**
     * setIsAppBackground
     *
     * @param isAppBackground
     */
    private void setIsAppBackground(boolean isAppBackground) {
        this.isAppBackground = isAppBackground;
    }

    /**
     * isAppBackground
     *
     * @return
     */
    private boolean isAppBackground() {
        return isAppBackground;
    }

    /**
     * jugeBackground
     *
     * @return
     */
    private boolean jugeBackground() {
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (null == appProcesses) {
            return false;
        }
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(getPackageName())) {
                if (appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    DPLogUtil.d("后台" + appProcess.processName);
                    return true;
                } else {
                    DPLogUtil.d("前台" + appProcess.processName);
                    return false;
                }
            }
        }
        return false;
    }

    /**
     * getRootView
     *
     * @return
     */
    public View getRootView() {
        return rootView;
    }

    /**
     * inflate
     *
     * @param layoutResId
     * @return
     */
    public View inflate(int layoutResId) {
        return inflater.inflate(layoutResId, null);
    }

    /**
     * F
     *
     * @param resId
     * @param <T>
     * @return
     */
    public <T extends View> T F(int resId) {
        View view;
        if (null == viewCacher.get(resId)) {
            view = F(getRootView(), resId);
        } else {
            view = viewCacher.get(resId);
        }
        return (T) view;
    }

    /**
     * F
     *
     * @param view
     * @param resId
     * @param <T>
     * @return
     */
    public <T extends View> T F(View view, int resId) {
        return null == view ? null : (T) view.findViewById(resId);
    }

    /**
     * $
     *
     * @param resId
     * @return
     */
    protected DPView $(int resId) {
        if (null == DPViewCacher.get(resId)) {
            DPViewCacher.put(resId, new DPView(F(resId)));
        }
        return DPViewCacher.get(resId);
    }

    /**
     * fromLayout
     *
     * @param layoutResId
     * @return
     */
    protected DPView fromLayout(int layoutResId) {
        if (null == DPViewCacher.get(layoutResId)) {
            DPViewCacher.put(layoutResId, new DPView(getLayoutInflater().inflate(layoutResId, null)));
        }
        return DPViewCacher.get(layoutResId);
    }

    /**
     * getRequestCode
     *
     * @param key
     * @return
     */
    public int getRequestCode(Integer key) {
        int requestCode;
        if (requestCodes.containsKey(key)) {
            requestCode = requestCodes.get(key);
        } else {
            requestCode = Long.valueOf(new Date().getTime()).intValue();
            requestCodes.put(key, requestCode);
        }
        return requestCode;
    }

    /**
     * startActivity
     *
     * @param cls
     * @param extras
     */
    public void startActivity(Class<?> cls, String... extras) {
        Intent intent = new Intent(this, cls);
        intent.putExtra(DPConsts.ACTIVITY_START_STRING_EXTRAS, extras);
        super.startActivity(intent);
    }

    /**
     * startActivityForResult
     *
     * @param cls
     * @param requestCode
     * @param data
     */
    public void startActivityForResult(Class<?> cls, int requestCode, String... data) {
        Intent intent = new Intent(this, cls);
        intent.putExtra(DPConsts.ACTIVITY_START_STRING_EXTRAS, data);
        super.startActivityForResult(intent, requestCode);
    }

    /**
     * finish
     *
     * @param resultCode
     * @param data
     */
    public void finish(int resultCode, String... data) {
        Intent intent = new Intent();
        intent.putExtra(DPConsts.ACTIVITY_RESULT_STRING_EXTRAS, data);
        setResult(resultCode, intent);
        super.finish();
    }

    /**
     * startActivityWithTaskCleared
     *
     * @param cls
     * @param extras
     */
    public void startActivityWithTaskCleared(Class<?> cls, String... extras) {
        finishAllActivities();
        Intent intent = new Intent(this, cls);
        intent.putExtra(DPConsts.ACTIVITY_START_STRING_EXTRAS, extras);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        super.startActivity(intent);
    }

    /**
     * onActivityResult
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        if (null != fragments) {
            for (Fragment fragment : fragments) {
                if (null == fragment) {
                    continue;
                }
                fragment.onActivityResult(requestCode, resultCode, data);
            }
        }
        if (null != data && data.hasExtra(DPConsts.ACTIVITY_RESULT_STRING_EXTRAS)) {
            onActivityResult(requestCode, resultCode, data.getStringArrayExtra(DPConsts.ACTIVITY_RESULT_STRING_EXTRAS));
        } else {
            onActivityResult(requestCode, resultCode, (String[]) null);
        }
    }

    /**
     * onActivityResult
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    protected void onActivityResult(int requestCode, int resultCode, String[] data) {

    }

    /**
     * getActivityStartExtra
     *
     * @return
     */
    public String[] getActivityStartExtra() {
        if (null == getIntent()) {
            return null;
        }
        return getIntent().getStringArrayExtra(DPConsts.ACTIVITY_START_STRING_EXTRAS);
    }

    /**
     * replaceFragment
     *
     * @param container
     * @param fragment
     * @param tag
     */
    public void replaceFragment(int container, Fragment fragment, String... tag) {
        if (isEmpty(tag)) {
            fragmentManager.beginTransaction().replace(container, fragment).commit();
        } else {
            fragmentManager.beginTransaction().replace(container, fragment, tag[0]).commit();
        }
    }

    /**
     * replaceFragment
     *
     * @param container
     * @param fragment
     * @param animEnter
     * @param animExit
     * @param tag
     */
    public void replaceFragment(int container, Fragment fragment, int animEnter, int animExit, String... tag) {
        if (isEmpty(tag)) {
            fragmentManager.beginTransaction().replace(container, fragment).setCustomAnimations(animEnter, animExit).commit();
        } else {
            fragmentManager.beginTransaction().replace(container, fragment, tag[0]).setCustomAnimations(animEnter, animExit).commit();
        }
    }

    /**
     * findFragmentByTag
     *
     * @param tag
     * @return
     */
    protected Fragment findFragmentByTag(String tag) {
        return fragmentManager.findFragmentByTag(tag);
    }

    /**
     * addFragment
     *
     * @param container
     * @param fragment
     * @param tag
     */
    protected void addFragment(int container, Fragment fragment, String... tag) {
        if (isEmpty(tag)) {
            fragmentManager.beginTransaction().add(container, fragment).commit();
        } else {
            fragmentManager.beginTransaction().add(container, fragment, tag[0]).commit();
        }
    }

    /**
     * addFragment
     *
     * @param container
     * @param id
     * @param fragment
     * @param tag
     */
    protected void addFragment(int container, int id, Fragment fragment, String... tag) {
        if (isEmpty(tag)) {
            fragmentManager.beginTransaction().add(container, fragment).commit();
        } else {
            fragmentManager.beginTransaction().add(container, fragment, tag[0]).commit();
        }
    }

    /**
     * showFragment
     *
     * @param fragment
     */
    protected void showFragment(Fragment fragment) {
        fragmentManager.beginTransaction().show(fragment).commit();
    }

    /**
     * hideFragment
     *
     * @param fragment
     */
    protected void hideFragment(Fragment fragment) {
        fragmentManager.beginTransaction().hide(fragment).commit();
    }

    /**
     * showFragment
     *
     * @param fragment
     * @param animEnter
     * @param animExit
     */
    protected void showFragment(Fragment fragment, int animEnter, int animExit) {
        fragmentManager.beginTransaction().show(fragment).setCustomAnimations(animEnter, animExit).commit();
    }

    /**
     * hideFragment
     *
     * @param fragment
     * @param animEnter
     * @param animExit
     */
    protected void hideFragment(Fragment fragment, int animEnter, int animExit) {
        fragmentManager.beginTransaction().hide(fragment).setCustomAnimations(animEnter, animExit).commit();
    }

    private Toast toast = null;

    /**
     * showToast
     *
     * @param resId
     * @param dependency
     */
    public void showToast(int resId, Boolean... dependency) {
        showToast(getString(resId), dependency);
    }

    /**
     * showToast
     *
     * @param msg
     * @param dependency
     */
    public void showToast(String msg, Boolean... dependency) {
        if (!isEmpty(dependency) && true == dependency[0]) {
            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        }
        if (null == toast) {
            toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
        } else {
            toast.setText(msg);
        }
        toast.show();
    }

    /**
     * isEmpty
     *
     * @param src
     * @return
     */
    protected static boolean isEmpty(String src) {
        return null == src || "".equals(src);
    }

    /**
     * isEmpty
     *
     * @param src
     * @param <T>
     * @return
     */
    protected static <T> boolean isEmpty(T[] src) {
        return null == src || 0 == src.length;
    }

    /**
     * isEmpty
     *
     * @param src
     * @return
     */
    protected static boolean isEmpty(List<?> src) {
        return null == src || 0 == src.size();
    }

    /**
     * isEmpty
     *
     * @param src
     * @return
     */
    protected static boolean isEmpty(Map<?, ?> src) {
        return null == src || 0 == src.size();
    }

    protected void exitApp() {
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }

    public String stringListToString(List<String> list) {
        return stringListToString(list, ",", false);
    }

    public String stringListToString(List<String> list, boolean trim) {
        return stringListToString(list, ",", trim);
    }

    public String stringListToString(List<String> list, String seperator) {
        return stringListToString(list, ",", false);
    }

    public String stringListToString(List<String> list, String seperator, boolean trim) {
        if (null == list) {
            return "";
        }
        String rt = "";
        for (String item : list) {
            if (trim) {
                item = item.trim();
            }
            rt += (seperator + item);
        }
        if (rt.endsWith(seperator)) {
            rt = rt.substring(0, rt.length() - seperator.length());
        }
        return rt;
    }

    public void toggleSoftInput() {
        mInputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public void showSoftInput(View view) {
        mInputMethodManager.showSoftInput(view, InputMethodManager.SHOW_FORCED);
    }

    public void hideSoftInput(View view) {
        mInputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    public void showShare(String title, String content, String url, String imgUrl) {
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

// 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle(title);
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl(url);
        // text是分享文本，所有平台都需要这个字段
        oks.setText(content);
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl(url);
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
//        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
//        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
//        oks.setSiteUrl("http://sharesdk.cn");

        if (null != imgUrl && !"".equals(imgUrl)) {
            oks.setImageUrl(imgUrl);
        }

        oks.setSilent(false);
// 启动分享GUI
        oks.show(this);
    }

    private Dialog confirmDialog;
    private DialogInterface.OnDismissListener settedOnConfirmDialogDismissListener;
    private DialogInterface.OnDismissListener onConfirmDialogDismissListener = new DialogInterface.OnDismissListener() {
        @Override
        public void onDismiss(DialogInterface dialog) {
            if (null != settedOnConfirmDialogDismissListener) {
                settedOnConfirmDialogDismissListener.onDismiss(dialog);
            }
            confirmDialog = null;
        }
    };

    public void hideConfirmDialog() {
        if (null != confirmDialog) {
            confirmDialog.dismiss();
        }
    }

    public void showConfirmDialog(Activity activity,
                                  String content,
                                  String leftButtonContent,
                                  String rightButtonContent,
                                  View.OnClickListener onLeftButtonClick,
                                  View.OnClickListener onRightButtonClick,
                                  DialogInterface.OnDismissListener onDismissListener) {
        hideConfirmDialog();

        settedOnConfirmDialogDismissListener = onDismissListener;

        View dialogView = getLayoutInflater().inflate(R.layout.dp_dialog_confirm, null);
        confirmDialog = new AlertDialog.Builder(activity).setView(dialogView).create();
        confirmDialog.setOnDismissListener(onConfirmDialogDismissListener);

        TextView contentTextView = (TextView) dialogView.findViewById(R.id.confirm_dialog_content);
        TextView leftButton = (TextView) dialogView.findViewById(R.id.confirm_dialog_left);
        TextView rightButton = (TextView) dialogView.findViewById(R.id.confirm_dialog_right);

        contentTextView.setText(content);
        leftButton.setText(leftButtonContent);
        rightButton.setText(rightButtonContent);

        if (null != onLeftButtonClick) {
            leftButton.setOnClickListener(onLeftButtonClick);
        }
        if (null != onRightButtonClick) {
            rightButton.setOnClickListener(onRightButtonClick);
        }
        confirmDialog.show();
    }

    public static void callSystemDialogAction(Context context, String phoneNumber) {
        Uri uri = Uri.parse(String.format("tel:%s", phoneNumber));
        Intent intent = new Intent(Intent.ACTION_DIAL, uri);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        try {
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            DPLogUtil.d("callSystemDialogAction exception: " + e.getMessage());
        }
    }
}
